<script setup lang="ts">
import type { ApprovalProcessDetail } from '@/types/api'
import { onLoad } from '@dcloudio/uni-app'
import { reactive, ref } from 'vue'
import { getTaskByProcessInstanceId } from '@/api/workflow'
import { formatDate } from '@/utils/timeUtils'

// 页面配置
definePage({
  style: {
    navigationBarTitleText: '审批结果',
    navigationBarTextStyle: 'black',
    backgroundColor: '#ffffff',
  },
})

// 页面参数
const params = ref<{
  taskId?: string
  processInstanceId?: string
  result?: string
  action?: string
  title?: string
  success?: string
}>({})

// 流程实例信息
const processInstance = reactive({
  title: '',
  instanceId: '',
  businessKey: '',
  initiator: '',
  initiatorName: '',
  createTime: '',
})

const idValue = ref('')
// 流程信息
const processInfo = reactive<ApprovalProcessDetail>({
  name: '-',
  nameDetail: '-',
  applyTime: '-',
  applyName: '-',
  busNumber: '-',
  status: 0,
  statusDesc: '-',
  processFlowNode: [],
})

// 加载状态
const loading = ref(false)

// 获取操作类型样式
function getActionStyle(action: string, success: boolean) {
  const baseStyles = {
    approve: { icon: '✓', bgColor: 'bg-emerald-50', textColor: 'text-emerald-600', borderColor: 'border-emerald-200' },
    reject: { icon: '✗', bgColor: 'bg-rose-50', textColor: 'text-rose-600', borderColor: 'border-rose-200' },
    delegate: { icon: '↗', bgColor: 'bg-blue-50', textColor: 'text-blue-600', borderColor: 'border-blue-200' },
    transfer: { icon: '⤴', bgColor: 'bg-blue-50', textColor: 'text-blue-600', borderColor: 'border-blue-200' },
    addSign: { icon: '+', bgColor: 'bg-orange-50', textColor: 'text-orange-600', borderColor: 'border-orange-200' },
  }

  const style = baseStyles[action as keyof typeof baseStyles] || baseStyles.approve

  // 如果失败，改为红色系
  if (!success) {
    return {
      ...style,
      bgColor: 'bg-rose-50',
      textColor: 'text-rose-600',
      borderColor: 'border-rose-200',
      icon: '✗',
    }
  }

  return style
}

// 监听页面加载
onLoad((options) => {
  params.value = options

  // 设置标题
  if (options.title) {
    processInstance.title = decodeURIComponent(options.title as string)
    uni.setNavigationBarTitle({
      title: `${processInstance.title} - 审批结果`,
    })
  }

  if (options.id) {
    idValue.value = options.id as string
  }
  // 加载流程数据
  loadProcessData()
})

// 模拟加载流程数据
async function loadProcessData() {
  try {
    loading.value = true
    const res = await getTaskByProcessInstanceId(idValue.value)
    if (res.data) {
      processInfo.name = res.data.name || '-'
      processInfo.nameDetail = res.data.nameDetail || '-'
      processInfo.applyTime = res.data.applyTime || '-'
      processInfo.applyName = res.data.applyName || '-'
      processInfo.busNumber = res.data.busNumber || '-'
      processInfo.status = res.data.status || 0
      processInfo.statusDesc = res.data.statusDesc || ''
      processInfo.processFlowNode = res.data.processFlowNode || []
    }
  }
  catch (error) {
    console.error('加载流程数据失败:', error)
    uni.showToast({
      title: '加载失败，请重试',
      icon: 'none',
    })
  }
  finally {
    loading.value = false
  }
}

// 跳转到待审批列表
function navigateToTodoList() {
  uni.switchTab({
    url: '/pages/list/todo',
  })
}

// 跳转详情
function navigateToDetail() {
  // 获取详情路径
  const path = getProcessDetailPath(processInfo.name, idValue.value, '')
  uni.navigateTo({
    url: path,
  })
}
</script>

<template>
  <view class="result-container min-h-screen bg-white">
    <!-- 加载状态 -->
    <view v-if="loading" class="h-60 flex items-center justify-center">
      <text class="text-gray-500">加载中...</text>
    </view>

    <template v-else>
      <!-- 操作结果展示 -->
      <view v-if="processInfo" class="mb-6">
        <!-- 结果状态卡片 - 白色主题 -->
        <view class="mx-4 mt-6 border border-gray-100 rounded-xl bg-white p-6 shadow-sm">
          <view class="text-center">
            <!-- 结果图标 -->
            <view
              class="mx-auto mb-4 h-20 w-20 flex items-center justify-center border-2 rounded-full"
              :class="[
                getActionStyle(processInfo.statusDesc, processInfo.status === 2).bgColor,
                getActionStyle(processInfo.statusDesc, processInfo.status === 2).borderColor,
                getActionStyle(processInfo.statusDesc, processInfo.status === 2).textColor,
              ]"
            >
              <text class="text-3xl font-bold">
                {{ getActionStyle(processInfo.statusDesc, processInfo.status === 2).icon }}
              </text>
            </view>

            <!-- 结果标题 -->
            <view class="mb-3">
              <text
                class="text-xl font-semibold"
                :class="processInfo.status === 2 ? 'text-emerald-600' : 'text-rose-600'"
              >
                {{ processInfo.status === 2 ? '操作成功' : '操作失败' }}
              </text>
            </view>

            <!-- 操作时间 -->
            <view class="text-sm text-gray-500">
              <text>操作时间：{{ formatDate(processInfo.applyTime, 'datetime_short') }}</text>
            </view>
          </view>
        </view>

        <!-- 详细信息 - 白色主题 -->
        <ProcessInfoCard :process-info="processInfo" />
      </view>

      <!-- 底部操作按钮 -->
      <view class="mt-8 p-4 space-y-3">
        <WdButton
          class="h-20 w-full rounded-lg bg-blue-600 text-white font-medium hover:bg-blue-700"
          @click="navigateToDetail"
        >
          查看流程详情
        </WdButton>

        <WdButton
          class="h-20 w-full border border-gray-200 rounded-lg bg-gray-50 text-gray-700 font-medium hover:bg-gray-100"
          @click="navigateToTodoList"
        >
          返回待审批列表
        </WdButton>
      </view>
    </template>
  </view>
</template>

<style lang="scss" scoped>
// 所有样式都已使用UnoCSS类实现，主题为白色
</style>
